package com.weijx.dishes.controller;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * com.weijx.dishes.controller.AuthController
 * 描述：
 * on 2025/11/7-上午9:56
 *
 * @author weijx
 */


@Controller
@RequestMapping("/api/auth")
public class AuthController {

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.appsecret}")
    private String appSecret;

    @GetMapping("/callback")
    public void handleCallback(
            @RequestParam(value = "code", required = false) String code, // [修改] code变为非必须
            @CookieValue(value = "user_openid", required = false) String userOpenId, // [新增] 从Cookie中读取openid
            HttpServletResponse response) throws IOException {

        // [核心修改] 增加健壮性判断
        // 如果用户的Cookie中已经有了openid，说明已经授权成功了，直接重定向到主页
        if (userOpenId != null && !userOpenId.isEmpty()) {
            System.out.println("用户已登录 (Cookie中存在OpenID)，直接重定向到主页。");
            response.sendRedirect("/");
            return; // 结束处理
        }

        // 如果Cookie中没有openid，但微信也没有传来code，说明是非法访问
        if (code == null || code.isEmpty()) {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("<h1>错误</h1><p>缺少微信授权码，请从公众号菜单进入。</p>");
            return;
        }

        // --- 只有在没有Cookie且有code的情况下，才执行以下授权流程 ---

        // 1. 根据code获取access_token和openid
        String url = String.format(
                "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                appId, appSecret, code
        );
        String result = HttpUtil.get(url);
        JSONObject json = JSON.parseObject(result);

        if (json.containsKey("openid")) {
            String openId = json.getString("openid");
            System.out.println("首次授权成功，获取到用户的OpenID: " + openId);

            // 2. 将 openId 存入 Cookie
            Cookie cookie = new Cookie("user_openid", URLEncoder.encode(openId, "UTF-8"));
            cookie.setPath("/");
            cookie.setMaxAge(3600 * 24 * 30);
            response.addCookie(cookie);

            // 3. 重定向到前端的点餐主页
            response.sendRedirect("/");
        } else {
            // 授权失败
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("<h1>微信授权失败</h1><p>错误信息：" + json.getString("errmsg") + "</p><p>请完全退出微信后重试。</p>");
        }
    }
}